package com.kun.index.controller;


import com.kun.common.Constants;
import com.kun.common.ResultDto;
import com.kun.common.annotation.PermissionAuthentication;
import com.kun.index.entity.Blog;
import com.kun.index.entity.Comment;
import com.kun.index.service.impl.BlogServiceImpl;
import com.kun.index.service.impl.CommentServiceImpl;
import com.kun.index.service.impl.UserServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author kunkun
 * @since 2024-03-12
 */
@RestController
@RequestMapping("/index/comment")
public class CommentController {

    @Autowired
    private CommentServiceImpl commentService;
    @Autowired
    private BlogServiceImpl blogService;

    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/commitComment")
    @ApiOperation("提交评论")
    public ResultDto commitComment(@RequestParam("blogId") Integer blogId,
                                   @RequestParam("userId") Integer userId,
                                   @RequestParam("content") String content){
        Comment comment = new Comment();
        comment.setBlogId(blogId);
        comment.setUserId(userId);
        comment.setContent(content);
        Integer num = commentService.insertComment(comment);
        return ResultDto.success(num);

    }

    @GetMapping("/queryAllComments")
    @ApiOperation("查询所有的评论")
    @PermissionAuthentication
    public ResultDto queryAllComments(@RequestParam(name = "queryCommentUserId", required=false)Integer queryCommentUserId,
                                      @RequestParam(name = "queryCommentBlogId", required=false)Integer queryCommentBlogId) {
        HashMap<String, Object> map = new HashMap<>();

        if (queryCommentUserId!=null){
            map.put("queryCommentUserId", queryCommentUserId);
        }
        if (queryCommentBlogId!=null){
            map.put("queryCommentBlogId", queryCommentBlogId);
        }
        Map<String, Object> resultMap = commentService.queryComments(map);

        if (((List<Comment>) resultMap.get("comments")).size() > 0) {
            ArrayList<Comment> comments = new ArrayList<>();
            comments= (ArrayList<Comment>) resultMap.get("comments");
            for (Comment comment : comments) {
//                对每个comment注入userNickname字段
                comment.setUserNickname(userService.queryUserById(comment.getUserId()).getNickname());
//                如果是根评论，则初始化ChildComments属性
                if (comment.getRId()==null){
                    ArrayList<Comment> list = new ArrayList<>();
                    comment.setChildComments(list);
                }
//                对每个comment注入userNickname字段
                Blog blog= blogService.queryBlogById(comment.getBlogId());
                comment.setBlogTitle(blog.getTitle());
            }
//                给comment对象设置子comment

            //1.筛选所有非根评论
            ArrayList<Comment> notRComments = new ArrayList<>();
            notRComments= (ArrayList<Comment>) comments.stream().filter(res->(res.getRId()!=null)).collect(Collectors.toList());
            //2.对于每个根评论设置其子评论
            for (Comment notRComment : notRComments) {
                for (Comment comment : comments) {
                    //2.1判断是否是根子关系
                    if (comment.getRId()==null && notRComment.getRId()==comment.getId()){
                        comment.getChildComments().add(notRComment);
                        break;
                    }
                }
            }
            //3.筛选所有的根评论
            comments = (ArrayList<Comment>) (comments).stream().filter(res -> (res.getRId() == null)).collect(Collectors.toList());
            resultMap.put("comments",comments);

            return ResultDto.success(resultMap);
        } else {
            return ResultDto.fail(Constants.CODE_301, "数据为空");
        }


    }



    @PostMapping("/commitFirstReply")
    @ApiOperation("提交第一次回复")
    public ResultDto commitFirstReply(@RequestBody Comment comment){
        Integer num = commentService.insertComment(comment);
        return ResultDto.success(num);

    }

    @GetMapping("/updateCommentReviewStatue")
    @ApiOperation("更新评论审核状态")
    public ResultDto updateCommentReviewStatue(@RequestParam("id") Integer commentId){
        Comment comment = commentService.queryCommentById(commentId);
        comment.setReviewStatue((comment.getReviewStatue()==1)?0:1);
        Integer num = commentService.updateComment(comment);
        if (num>0){
            return ResultDto.success("更新成功");
        }else {
            return ResultDto.fail("更新失败");
        }
    }

    @GetMapping("/queryComments")
    @ApiOperation("通过博客id查询评论")
    public ResultDto queryComments(@RequestParam("blogId") Integer blogId){

        List<Comment> comments = commentService.queryCommentsByBlogId(blogId);
        for (Comment comment : comments) {
            comment.setUserNickname(userService.queryUserById(comment.getUserId()).getNickname());
            comment.setUserAvatarUrl(userService.queryUserById(comment.getUserId()).getAvatarUrl());
            if (comment.getRId()==null){
                ArrayList<Comment> list = new ArrayList<>();
                comment.setChildComments(list);
            }
            if (comment.getPId()!=null){
                Integer userId = commentService.queryCommentById(comment.getPId()).getUserId();
                comment.setPNickname(userService.queryUserById(userId).getNickname());
            }

        }
        //筛选所有非根评论
        ArrayList<Comment> notRComments = new ArrayList<>();
        notRComments=(ArrayList<Comment>)comments.stream().filter(res->(res.getRId()!=null)).collect(Collectors.toList());
        //对于每个根评论设置其子评论
        for (Comment notRComment : notRComments) {
            for (Comment comment : comments) {
                if (comment.getRId()==null && notRComment.getRId()==comment.getId()){
                    comment.getChildComments().add(notRComment);
                    break;
                }
            }
        }
        comments=(ArrayList<Comment>)comments.stream().filter(res->(res.getRId()==null)).collect(Collectors.toList());

        return ResultDto.success(comments);

    }


    @PostMapping("/batchDeleteComment")
    @ApiOperation("批量删除评论")
    public ResultDto batchDeleteComment(@RequestBody List<Integer> ids){
        int num = commentService.batchDeleteComment(ids);
        if (num>0){
            return ResultDto.success("删除评论成功");
        }else{
            return ResultDto.fail("删除评论失败");
        }


    }

    @GetMapping("/deleteComment")
    @ApiOperation("删除评论")
    public ResultDto deleteComment(@RequestParam("id") Integer id){

        Comment comment = commentService.queryCommentById(id);
        int num=0;
        if (comment.getRId()==null){        //1.如果该评论为根节点
            List<Comment> comments= commentService.queryCommentsByRid(id);          //1.1删除所有的子节点
            for (Comment comment1 : comments) {
                commentService.deleteCommentById(comment1.getId());
                num++;
            }
            commentService.deleteCommentById(id);                       //1.2删除根节点
        }else{        //2.非根节点

            commentService.recursionDeleteNotRootComments(comment);
            num+=1;
        }

        if (num>0){
            return ResultDto.success("删除评论成功");
        }else{
            return ResultDto.fail("删除评论失败");
        }
    }





}

